package com.loongson;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.loongson.ApplicationLocal;
// import cn.com.loongcloud.loongcloudav.icon.ExtractIcon;


public class AppUtils {
	 // 获取文件创建日期的方法
	public  LocalDate getCreationDate(Path path) {
       try {
           BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
           Instant instant = attributes.creationTime().toInstant();
           return instant.atZone(ZoneId.systemDefault()).toLocalDate();
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
   }
	public  List<ApplicationLocal> scanStartMenuShortcuts() throws Exception {

       List<ApplicationLocal> resultList = new ArrayList<>();

       String[] startMenuFolders = {
               "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs",
               "C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs"
       };
       
       LocalDate filterDate = LocalDate.of(2024, 6, 1);
   		List<String> commandList = new ArrayList<String>();
       for (String folder : startMenuFolders) {
   		Collection<File> lnkFiles = FileUtils.listFiles(new File(folder), new String[]{"lnk"}, true);
   		// 遍历找到的LNK文件并输出它们的路径
   		for (File lnkFile : lnkFiles) {
   			 Path path = lnkFile.toPath();
   			 String filename = path.toString();
   			 if(filename.contains("卸载") ||filename.contains("uni")  ||filename.contains("Uni") || filename.contains("Setup")) {
   				 continue;
   			 }
   			 LocalDate creationDate = getCreationDate(path);
                if (creationDate != null && creationDate.isAfter(filterDate)) {
                
                	String command =  " \"(New-Object -ComObject WScript.Shell).CreateShortcut('"+path + "').TargetPath\"";
                	commandList.add(command);
             	   ApplicationLocal app = new ApplicationLocal();
            	   app.setAppname(lnkFile.getName().substring(0, lnkFile.getName().lastIndexOf('.')));
            	   resultList.add(app);
                } 	
   		}        
   
       }
       List<String> resultExePath = executePowerShellCommands(commandList);
       for (int i=0;i<resultExePath.size();i++) {
    	   String str = resultExePath.get(i);
    	   if(str.endsWith("exe")) {
    		   resultList.get(i).setAppPath(str);    		
    		   resultList.get(i).setIcon(AppIcon.extractIcon(str));
    	   }    	   
       }

      Iterator<ApplicationLocal> iterator = resultList.iterator();
       while (iterator.hasNext()) {
    	   ApplicationLocal app = iterator.next();
    	   if(app.getAppPath() == null || !app.getAppPath().endsWith("exe") || !new File(app.getAppPath()).exists()|| app.getAppPath().contains("Sogou")) {
    		   iterator.remove(); 
    	   } 
       }
       

       return resultList;
   }

   
   private  List<String> executePowerShellCommands(List<String> commandList) {

       List<String> result = new ArrayList<String>();
       try {
    	   ProcessBuilder processBuilder = new ProcessBuilder("powershell.exe", "-Command", String.join(";", commandList.toArray(new String[0])));
      
           processBuilder.redirectErrorStream(true);
           Process process = processBuilder.start();

           // Read output
           BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
           String line;
           while ((line = reader.readLine()) != null) {
               result.add(line);
           }

           process.waitFor();
           process.destroy();

       } catch (IOException | InterruptedException e) {
           e.printStackTrace();
       }
       return result;
   }
	public static void main(String[] args) {
		
	    
		// TODO Auto-generated method stub
		// File file = new File("C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Google Chrome.lnk");
		AppUtils appUtils = new AppUtils();


		
        try {
        	System.out.println(appUtils.scanStartMenuShortcuts());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        ;

	}

}
